package com.example.blog.common.aop;

import com.alibaba.fastjson.JSON;
import com.example.blog.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.Duration;

@Aspect
@Component
@Slf4j
//缓存的切面(切点为添加了该注解的方法)
public class CacheAspect {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //加了该注解就成为了一个切点
    @Pointcut("@annotation(com.example.blog.common.aop.Cache)")
    public void pt() {
    }

    @Around("pt()")//环绕通知
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            Signature signature = joinPoint.getSignature();
            //获取切点的类名
            String className = joinPoint.getTarget().getClass().getSimpleName();
            //获取切点的方法名
            String methodName = signature.getName();

            //获取切点的参数
            Class[] parameterTypes = new Class[joinPoint.getArgs().length];//存储参数类型的数组
            Object[] args = joinPoint.getArgs();//存储参数的数组
            String params = "";
            for (int i = 0; i < args.length; i++) {
                if (args[i] != null) {
                    params += JSON.toJSONString(args[i]);
                    parameterTypes[i] = args[i].getClass();
                } else {
                    parameterTypes[i] = null;
                }
            }
            if (StringUtils.isNotEmpty(params)) {
                //MD5加密 以防出现key过长以及字符串转义获取不到的情况
                params = DigestUtils.md5Hex(params);
            }
            //通过parameterTypes获得切点
            Method method = joinPoint.getSignature().getDeclaringType().getMethod(methodName, parameterTypes);
            //获得cache注解
            Cache annotation = method.getAnnotation(Cache.class);
            //拿到切点设置的缓存过期时间
            long expire = annotation.expire();
            //拿到切点设置的缓存名称
            String name = annotation.name();
            //先从redis获得，看是否该缓存存入了redis
            String redisKey = name + "::" + className + "::" + methodName + "::" + params;
            String redisValue = redisTemplate.opsForValue().get(redisKey);
            if (StringUtils.isNotEmpty(redisValue)) {
                log.info("走了缓存~~~,{},{}", className, methodName);
                return JSON.parseObject(redisValue, Result.class);
            }
            //如果为空，代表需要调用切点方法,再把返回值存入redis里面
            Object proceed = joinPoint.proceed();
            redisTemplate.opsForValue().set(redisKey, JSON.toJSONString(proceed), Duration.ofMillis(expire));
            log.info("存入缓存~~~ {},{}", className, methodName);
            return proceed;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return Result.fail(-999, "系统错误");
    }
}
